const cartmodel = require('../db/cart');
const goodsmodel = require('../db/goods')
const respond = require('../utils/respond')

module.exports = {
    getAllGoods: async (req, res) => {
        let { page, size } = req.params
        console.log(page, size);
        if (!page) {
            respond(res, 1, '缺少当前页的参数')
            return
        }
        //分页查询
        let docs = await goodsmodel.find({}, { __v: 0 }, { skip: (page - 1) * size, limit: size })
        if (!docs.length) {
            respond(res, 2, '获取商品数据失败')
            return
        }
        //返回页码数
        let total = await goodsmodel.count()
        let totalPage = Math.ceil(total / size)
        respond(res, 0, '获取商品数据成功', {
            data: docs,
            totalPage
        })


    },

    goodsDetail: async (req, res) => {
        // 接收前端传递的id
        let { id } = req.params

        //从数据中获取一条数据
        let docs = await goodsmodel.findOne({ '_id': id })

        console.log(docs);
        if (!docs) {
            respond(res, 1, '获取失败')
            return
        }
        respond(res, 0, '获取成功', {
            data: docs
        })
    },

    goodscart: async (req, res) => {
        let { _id } = req.params
        let userid = _id
        let docs = await cartmodel.find({ userid }, { __v: 0 })
        if (!docs.length) {
            respond(res, 2, '获取商品数据失败')
            return
        }
        respond(res, 0, '获取商品数据成功', docs)
    },
    cartgoods: async (req, res) => {
        // console.log('cartgoods');
        const goodsid = Object.values(req.query);
        // console.log(goodsid);
        var info = {}
        var tp = 0
        for(var i=0;i<goodsid.length;i++){
            // console.log(goodsid[i]);
            let doc = await goodsmodel.find({_id:goodsid[i]}, { __v: 0 })
            if(doc){
                console.log('查找到数据了');
                Object.assign(info,doc)
            }else{
                console.log('数据不存在');
            }
            tp++
            if(tp==goodsid.length){
                respond(res,0,'',info)
            }
        }
        
    }
}